/* eslint-disable max-len */
/* eslint-disable no-multiple-empty-lines */
/* eslint-disable prettier/prettier */
/* eslint-disable react/jsx-one-expression-per-line */
/* eslint-disable react/destructuring-assignment */
/* eslint-disable react/jsx-closing-tag-location */
/* eslint-disable react-native/no-unused-styles */
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import { View, Image, StyleSheet, Text, AppState } from 'react-native';
import { connect } from 'react-redux';
import {
  RotationView,
  Utils,
  SliderWithLine,
  SwitchButton,
  Button,
  NotificationLegacy,
  Notification,
  Modal,
  TYSdk,
  Toast,
} from 'tuya-panel-kit';
import FadeDot from './main-fadeDot';
import FadeSnow from './main-fadeSnow';
import CenterTip from './main-centerTip';
import dpCodes from '../../config/dpCodes';
import Res from '../../res';
import icons from '../../res/iconfont.json';
import { timeoutWith } from 'rxjs-compat/operator/timeoutWith';
import Snowing from './main-snowing';
import { debounce } from '../../utils';

const TYDevice = TYSdk.device;
const { convertX: cx, convertY: cy, width } = Utils.RatioUtils;

const {
  power: powerCode,
  mode: modeCode,
  tempSet: tempSetCode,
  tempCurrent: tempCurrentCode,
  vertical: verticalCode,
  anion: anionCode,
  fault: faultCode,
  light: lightCode,
} = dpCodes;
console.log('mainViewdpCodes', dpCodes);

const duration = 3200;

class HomeMainView extends PureComponent {

  static defaultProps = {
    power: false,
    tempSet: 18,
    fault: 0,
  };

  constructor(props) {
    super(props);
    const { tempSet } = this.props;
    console.log('props', this.props);
    this.maxValue = tempSet - 18;
    this.sliderLineWidth = width - 40 - 20;
    this.state = {
      temp: tempSet,
    };
    this.flage = false;

  }




  componentWillMount() {
    console.log('Component WILL MOUNT!');


    this.timer2 = setTimeout(() => {
      // 用于查询设备状态
      console.log('查询设备状态');
      TYDevice.putDeviceData({
        [lightCode]: true,
      });
    }, 1000);
  }

  componentDidMount() {

    AppState.addEventListener('change', this._handleAppStateChange);
    TYSdk.event.on('deviceDataChange', data => {
      // console.log('addEventListener', data);
      if (data.type === 'dpData') {
        this._handleDpDataChange(data.payload);
      }
    });
  }

  componentWillUnmount() {

    console.log('Component Will Unmount!');
    this.timer && clearTimeout(this.timer);
    this.timer2 && clearTimeout(this.timer2);
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleDpDataChange = data => {
    const cmd = {};
    const codes = Object.keys(data);
    // console.log('收到数据上报');
    codes.forEach(code => {
      const { [code]: something } = this.state;
      if (typeof something !== 'undefined') {
        cmd[code] = data[code];
      }
    });

    if (Object.keys(cmd).length > 0) {
      this.setState(cmd);
    }
  };

  _handleAppStateChange = (nextAppState) => {
    if (nextAppState != null && nextAppState === 'active') {
      // 如果是true ，表示从后台进入了前台 ，请求数据，刷新页面。或者做其他的逻辑

      if (this.flage) {
        console.log('从后台进入前台');
        // 这里的逻辑表示 ，第一次进入前台的时候 ，不会进入这个判断语句中。
        // 因为初始化的时候是false ，当进入后台的时候 ，flag才是true ，
        // 当第二次进入前台的时候 ，这里就是true ，就走进来了。
        // 测试通过
        // alert("从后台进入前台");
        // 这个地方进行网络请求等其他逻辑。

        const { fault } = this.props;
        this.timer = setTimeout(() => {
          faultError(fault);
        }, 500);

        console.log('查询设备状态');
        // 用于查询设备状态
        TYDevice.putDeviceData({
          [lightCode]: true,
        });
      }
      this.flage = false;
    } else if (nextAppState != null && nextAppState === 'background') {
      this.flage = true;
    }
  }

  coldClicked = debounce(() => {

    console.log('制冷');
    TYDevice.putDeviceData({
      [modeCode]: 'cold',
    });
  });

  dryClicked = debounce(() => {
    console.log('除湿');
    TYDevice.putDeviceData({
      [modeCode]: 'dry',
    });
  });

  windClicked = debounce(() => {
    console.log('送风');
    TYDevice.putDeviceData({
      [modeCode]: 'wind',
    });
  });


  sliderClicked = debounce(v => {
    console.log('调节温度', v);
    TYDevice.putDeviceData({
      [tempSetCode]: v,
    });
  });

  verticalClicked = debounce(v => {
    console.log('摆风', v);
    TYDevice.putDeviceData({
      [verticalCode]: v,
    });
  });

  anionClicked = debounce(v => {
    console.log('负离子', v);
    TYDevice.putDeviceData({
      [anionCode]: v,
    });
  });

  render() {
    const { power, mode, tempSet, vertical, anion, fault } = this.props;
    return (
      <View>
        {faultError(fault)}
        <RotationView style={styles.container} active={power} duration={duration}>
          <Image
            style={styles.image}
            resizeMode="contain"
            source={power ? Res.display : Res.displayOff}
          />
        </RotationView>

        {/* 下雪动画 */}
        {power && mode === 'cold' && <Snowing style={styles.snowContainer} />}
        {/* 下雪动画，弃用 */}
        {/* {power && mode === 'cold' && <FadeSnow active={power} duration={duration} />} */}
        {/* 除湿动画 */}
        {power && mode === 'dry' ? <FadeDot active={power} duration={duration} /> : null}


        {/* 模式 */}
        <View style={styles.mode}>
          <Button
            iconColor="#fff"
            size={24}
            style={{
              width: cx(40),
              height: cx(40),
            }}
            image={mode === 'cold' ? (power ? Res.coldSel : Res.coldDis) : Res.cold}
            imageStyle={styles.icon}
            text="制冷"
            textStyle={{
              color: mode === 'cold' ? '#4296F5' : '#777777',
              fontSize: 12,
            }}
            onPress={() => {
              if (power) {
                this.coldClicked();
              }
            }}
          />
          <Button
            iconColor="#fff"
            size={24}
            style={{
              width: cx(40),
              height: cx(40),
            }}
            image={mode === 'dry' ? (power ? Res.drySel : Res.dryDis) : Res.dry}
            imageStyle={styles.icon}
            text="除湿"
            textStyle={{
              color: mode === 'dry' ? '#4296F5' : '#777777',
              fontSize: 12,
            }}
            onPress={() => {
              if (power) {
                this.dryClicked();
              }
            }}
          />
          <Button
            iconColor="#fff"
            size={24}
            style={{
              width: cx(40),
              height: cx(40),
            }}
            image={mode === 'wind' ? (power ? Res.windSel : Res.windDis) : Res.wind}
            imageStyle={styles.icon}
            text="送风"
            textStyle={{
              color: mode === 'wind' ? '#4296F5' : '#777777',
              fontSize: 12,
            }}
            onPress={() => {
              if (power) {
                this.windClicked();
              }
            }}
          />
        </View>

        {/* 调节温度  用this.start.temp 数据上报没有更新*/}
        <View style={styles.temp}>
          <Text
            style={[styles.baseText, { fontSize: 12 }, { marginTop: 5 }]}
          >{`  调节温度  ${tempSet}℃`}</Text>

          <SliderWithLine
            style={{ marginTop: 5, marginBottom: 10, marginHorizontal: 10 }}
            width={this.sliderLineWidth}
            height={cx(45)}
            nounWidth={2}
            nounNumber={8}
            nounColor="#4296F5" // 刻度 && 文字颜色
            activeNounColor="#FFFFFF" // 激活刻度 && 文字颜色
            backgroundColor="#edf2f8" // 滑动条背景色
            activeBackgroundColor="#4296F5" // 滑动条激活背景色
            startText="18℃" // 开始文案
            endText="28℃" // 结束文案
            fontSize={cx(13)}
            stepValue={1}
            min={18}
            max={28}
            minValue={0}
            maxValue={tempSet - 18}
            maxDisabled={true}
            disabled={mode !== 'cold' || !power} // 制冷模式下才能调节温度
            onValueChange={value => {
              this.setState({
                temp: value.maxValue,
              });
            }}
            onSlidingComplete={value => {
              this.setState({
                temp: value.maxValue,
              });
              this.sliderClicked(value.maxValue);
            }}
          />
        </View>

        {/* 摆风、负离子 */}
        <View style={styles.switchView}>
          <View style={[styles.switchSubView, { marginEnd: 5 }]}>
            <View style={{ flexDirection: 'row', alignItems: 'center', marginStart: 10 }}>
              <Image style={styles.icon} source={Res.vertical} />
              <Text style={[styles.baseText, { fontSize: 14 }, { color: vertical ? '#4296F5' : '#777777' }]}>摆风</Text>
            </View>

            <SwitchButton
              style={{ marginEnd: 10 }}
              value={vertical}
              size={{ width: 37, height: 19, activeSize: 17 }}
              theme={{ onTintColor: '#57BCFB', tintColor: '#bad2f3' }}
              onValueChange={v => {
                if (power) {
                  this.verticalClicked(v);
                }
              }}
            />
          </View>

          <View style={[styles.switchSubView, { marginStart: 5 }]}>
            <View style={{ flexDirection: 'row', alignItems: 'center', marginStart: 10 }}>
              <Image style={styles.icon} source={Res.anion} />
              <Text style={[styles.baseText, { fontSize: 14 }, { color: anion ? '#4296F5' : '#777777' }]}>负离子</Text>
            </View>

            <SwitchButton
              style={{ marginEnd: 10 }}
              value={anion}
              size={{ width: 37, height: 19, activeSize: 17 }}
              theme={{ onTintColor: '#57BCFB', tintColor: '#bad2f3' }}
              onValueChange={v => {
                if (power) {
                  this.anionClicked(v);
                }
              }}
            />
          </View>
        </View>
        <CenterTip />
      </View>
    );
  }
}

function faultError(error) {

  if (error === 0) {
    Notification.hide();
    return;
  }

  const errorBinary = error.toString(2);
  const newStr = errorBinary.split('').reverse().join('');
  console.log(newStr);

  let errorString = '';

  for (let i = 0; i < newStr.length; i++) {
    const err = newStr[i];

    if (err === '1') {

      console.log('error', i, errorList[i]);

      if (errorString === '') {
        errorString = errorList[i];
      } else {
        errorString = `${errorString}\n${errorList[i]}`;
      }
    }
  }

  Notification.show({
    message: errorString,
    variant: 'warning',
    style: { marginTop: 10 },
  });
}



const errorList = [
  '水泵保护中！',
  '满水故障，请倒水！',
  '高温故障，请将设备放置在较低环境温度下工作！',
  '防冻结保护中！',
  '防冻结保护中！',
  '环温传感器故障，请联系售后！',
  '管温传感器故障，请联系售后！',
  '冷媒泄露，请联系售后！',
  '温湿度模块故障，请联系售后！'];

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    marginVertical: cy(30),
  },

  error: {
    width: '80',
  },

  snowContainer: {
    flexDirection: 'row',
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
  },
  mode: {
    flexDirection: 'row',
    backgroundColor: 'rgba(229,237,247,1)',
    height: 80,
    marginTop: 40,
    marginHorizontal: 20,
    borderRadius: 12,
    justifyContent: 'space-around', // 子控件平分
  },

  temp: {
    alignSelf: 'stretch',
    backgroundColor: 'rgba(229,237,247,1)',
    // height: 90,
    marginTop: 10,
    marginHorizontal: 20,
    borderRadius: 12,
  },

  switchView: {
    flexDirection: 'row',
    // backgroundColor: 'rgba(255,255,255,1)',
    marginTop: 10,
    marginHorizontal: 20,
    marginBottom: 10,
    borderRadius: 12,
  },

  // 摆风、负离子
  switchSubView: {
    flexDirection: 'row',
    // justifyContent: 'center', // 子视图垂直居中
    alignItems: 'center', // 子视图水平居中
    backgroundColor: 'rgba(229,237,247,1)',
    flex: 1,
    justifyContent: 'space-between',
    height: 65,
    borderRadius: 12,
  },

  // 旋转图片样式
  image: {
    tintColor: '#6FBCFB',
    width: width * 0.6,
    height: width * 0.6,
  },
  // 图标样式
  icon: {
    // tintColor: '#5792C8',
    width: 32,
    height: 32,
    // resizeMode: 'center',
    // marginStart: 10,
  },

  baseText: {
    fontFamily: 'Cochin',
    // textAlign: 'center',
    color: 'rgb(145,148,150)',
    marginStart: 10,
  },
});

export default connect(({ dpState }) => ({
  power: dpState[powerCode],
  mode: dpState[modeCode],
  tempSet: dpState[tempSetCode],
  vertical: dpState[verticalCode],
  anion: dpState[anionCode],
  fault: dpState[faultCode],
  light: dpState[lightCode],
}))(HomeMainView);
